import React, {useEffect, useState} from "react";
import {withRouter} from "react-router-dom";
import PropTypes from "prop-types"
import PubSub from 'pubsub-js'
import queryString from "query-string";
import List from "./List";
import Grid from "./Grid";
import Modal from "../Modal";
import fileNodeApi from "../../api/fileNode";

import emptySVG from "../../assets/img/empty.svg"

import './index.scss'
import ToolBar from "../ToolBar";



function Directory(props) {
    const [layout, setLayout] = useState('list')
    const [fileNode, setFileNode] = useState(null)
    const [selectList, setSelectList] = useState([])
    const [visible, setVisible] = useState(false)
    const [name, setName] = useState('')

    useEffect(() => {
        PubSub.subscribe('EV_FLASH_FILE_NODE', () => {
            let path = queryString.parse(props.location.search).path
            fileNodeApi.getByPath(path || '').then(resp => {
                setFileNode(resp.data)
            })
        })
        let path = ''
        if (props.location.search.length !== 0) {
            path = queryString.parse(props.location.search).path
        }
        fileNodeApi.getByPath(path).then(resp => {
            setFileNode(resp.data)
        })
    }, [props.location.search])
    
    useEffect(() => {
        PubSub.subscribe('EV_CHANGE_LAYOUT', (_, data) => {
            setLayout(data)
        })
    }, [])

    useEffect(() => {
        PubSub.subscribe('EV_SELECT', (_, data) => {
            setSelectList(data)
        })
    }, [])

    useEffect(() => {
        PubSub.subscribe('EV_NEW_FOLDER', () => {
            setVisible(!visible)
        })
    }, [visible])

    useEffect(() => {
        PubSub.unsubscribe('EV_FILE_NODE_DEL')
        PubSub.subscribe('EV_FILE_NODE_DEL', () => {
            fileNodeApi.delByIds(selectList).then(resp => {
                const children = fileNode.children.filter(fn => selectList.indexOf(fn.id) === -1)
                setFileNode({...fileNode, children})
                setSelectList([])
            })
        })
    },[fileNode, selectList])

    useEffect(() => {
        PubSub.unsubscribe('EV_FILE_DOWNLOAD')
        PubSub.subscribe('EV_FILE_DOWNLOAD', () => {
            let a = document.createElement('a')
            fileNode.children.filter(fileNode => {
                return selectList.indexOf(fileNode.id) >= 0
            }).forEach(fileNode => {
                a.setAttribute('href', '/api/netdisk/f/download/' + fileNode.id)
                a.setAttribute('download', fileNode.name)
                a.click()
            })
        })
    }, [fileNode, selectList])

    function change({target}) {
        const value = target.value.trim()
        setName(value)
    }

    function render() {
        return (
            <label className={ 'new-folder' } >
                <input type={ 'text' } value={ name } onChange={ change  } />
            </label>
        )
    }

    function submit() {
        fileNodeApi.mkdir({
            name: name,
            parentId: fileNode.id
        }).then(resp => {
            /*[resp.data, ...data]*/
            /*file.children.unshift(resp.data)*/
            setFileNode({...fileNode, children: [resp.data, ...fileNode.children]})
        })

        setName('')
        setVisible(!visible)
    }

    function cancel() {
        setName('')
        setVisible(!visible)
    }

    return (
        <>
            <ToolBar style={{paddingLeft: '10px'}} root={ fileNode } selectList={ selectList } />
            {/*<Path />*/}
            <div style={ props.style } className={ 'dir-warp ' + props.className }>
                {
                    fileNode !== null
                    ? (
                            fileNode.children.length > 0
                                ? (layout === 'list' ? (<List data={ fileNode.children } />) : (<Grid data={ fileNode.children } />))
                                : (
                                    <div className='empty'>
                                        <img src={ emptySVG } alt={ 'empty' } />
                                        <div> 您还没上传过文件哦，点击 <span>上传</span> 按钮～ </div>
                                    </div>
                                )
                        )
                    : (<></>)
                }
            </div>
            <Modal visible={ visible }
                   title={ '创建文件夹' }
                   render={ render }
                   submit={ submit }
                   cancel={ cancel }
            />
        </>
    )
}

Directory.propTypes = {
    style: PropTypes.object,
    className: PropTypes.string
}

Directory.defaultProps = {
    style: {},
    className: ''
}

export default withRouter(Directory)